package com.edu.study.service;

import com.edu.study.dao.UserDao;
import com.edu.study.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by liyih on 2017/4/8.
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;

    public User saveUser(User user) {
        if (user == null)
            throw new NullPointerException("user is null");
        return userDao.save(user);
    }

    public Page<User> userList(int page, int pageSize) {
        if (page <= 0)
            page = 1;
        if (pageSize <= 0)
            pageSize = 40;
        Page<User> list = userDao.findAll(pageRequest(page - 1, pageSize, sort()));
        return list;
    }

    private PageRequest pageRequest(int page, int pageSize, Sort sort) {
        return new PageRequest(page, pageSize, sort);
    }

    private Sort sort() {
        return new Sort(Sort.Direction.DESC,"ctime");
    }

}
